import React, { useEffect, useState } from "react";
import {
  Button,
  Modal,
  Input,
  message,
  Empty,
  Spin,
  Popconfirm,
  Select,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  PlayCircleOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { useStore } from "@/store";
import { nanoid } from "nanoid";
import StorageManager from "@/utils/StorageManager";
import { setStore, getStore, slideLoginOut } from "@/services/system.service";
import SuoLueTu from "./SuoLueTu";
import { useNavigate } from "react-router-dom";

const SlideList = () => {
  const {
    slideFatnerList,
    slideList,
    setCurrentSlideIndex,
    currentSlideIndex,
    updateSlide,
    setCurrentPresentation,
    updateSlideTitle,
    updateAnyData,
  } = useStore();
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const [inputValue2, setInputValue2] = useState("");
  const [selectValue, setSelectValue] = useState("color");
  const [backgroundVal, setbackgroundVal] = useState("");
  const [backgroundVal2, setbackgroundVal2] = useState("");
  const [storeData, setStoreData] = useState(null);
  const navigate = useNavigate();

  const queryData = () => {
    setLoading(true);
    getStore().then((res) => {
      setLoading(false);
      // eslint-disable-next-line
      if (res && res?.hasOwnProperty("store")) {
        if (res?.store && res?.store?.length > 0) {
          // 有值的情况
          updateAnyData({
            slideFatnerList: res?.store || [],
            sildeFatherId: "",
          });
          setStoreData(res?.store);
          StorageManager.setSessionStorageSimpleSync(
            "storage-store",
            JSON.stringify(res?.store || {})
          );
          updateSlide(res?.store?.slideList || []);
          updateSlideTitle(res?.store?.slideTitle || "");
          setCurrentPresentation(res?.store?.slideList?.length > 0 ? 1 : 0);
        } else {
          // 无值的情况
          updateAnyData({
            slideFatnerList: [],
            sildeFatherId: "",
          });
          updateSlide([
            {
              sortId: 1,
              id: nanoid(),
              elements: [],
            },
          ]);
          updateSlideTitle("");
          setCurrentPresentation(1);
        }
      } else {
        message.error("请先进行登录");
        navigate("/login");
      }
    });
  };

  useEffect(() => {
    queryData();
  }, []);

  const gotoCancle = (fatherIndex) => {
    setLoading(true);
    const slideFatnerListBro = slideFatnerList.filter(
      (item, index) => index !== fatherIndex
    );
    setStore({ store: slideFatnerListBro }).then((res) => {
      setLoading(false);
      message.success("删除成功");
      queryData();
    });
  };

  const handleCancel = () => {
    setModalVisible(false);
    setInputValue("");
  };

  const handleOK = () => {
    if (!inputValue) {
      message.error("请输入幻灯片标题");
      return;
    }
    // if (selectValue === "color" && !backgroundVal) {
    //   message.error("请设置背景颜色");
    //   return;
    // }
    // if (selectValue === "gradient" && (!backgroundVal || !backgroundVal2)) {
    //   message.error("请设置背景渐变颜色");
    //   return;
    // }
    // if (selectValue === "img" && !backgroundVal) {
    //   message.error("请设置背景图片");
    //   return;
    // }
    setModalVisible(false);
    const id = nanoid();
    navigate(`/slide/detail?title=${inputValue}`);
    updateAnyData({
      sildeFatherId: id,
      slideTitle: inputValue,
      slideImage: inputValue2,
      sildeBgType: selectValue,
      sildeBgVal: backgroundVal,
      sildeBgVal2: backgroundVal2,
    });
    handleCancel();
  };

  const handleOut = async () => {
    // 登录
    const res = await slideLoginOut();
    if (res) {
      message.success("退出登录成功");
      setTimeout(() => {
        navigate("/login");
        StorageManager.removeSessionStorageSync("storage-token");
        StorageManager.removeSessionStorageSync("storage-email");
        StorageManager.clearSessionStorageSync();
      });
    }
  };

  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        padding: "32px",
        paddingTop: "16px",
        overflowY: "scroll",
        backgroundColor: "#f3f4f6",
      }}
    >
      <Spin spinning={loading}>
        <>
          <div
            style={{
              margin: "0 auto",
              display: "flex",
              width: "1300px",
              justifyContent: "space-between",
              marginBottom: "20px",
              paddingRight: "40px",
            }}
          >
            <Button
              key="add"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setModalVisible(true);
              }}
            >
              新演示
            </Button>
            <Button
              key="退出登录"
              type="dashed"
              onClick={() => {
                handleOut();
              }}
            >
              退出登录
            </Button>
          </div>
          {slideFatnerList && slideFatnerList?.length > 0 ? (
            <div
              style={{
                display: "flex",
                flexWrap: "wrap",
                justifyContent: " left",
                width: 1300,
                margin: "0 auto",
              }}
            >
              {slideFatnerList?.map((fatherItem, fatherIndex) => {
                return (
                  <div key={fatherItem.id}>
                    <div
                      style={{
                        width: 400,
                        height: 280,
                        margin: "0 30px 30px 0",
                        overflow: "hidden",
                        borderRadius: 10,
                        boxShadow: "0 0 6px rgba(0, 0, 0, 0.25)",
                      }}
                    >
                      <div
                        style={{
                          width: "100%",
                          height: 200,
                          // backgroundColor: "white",
                          background: fatherItem?.slideImage
                            ? `url(${fatherItem?.slideImage}) 0% 0% / cover no-repeat`
                            : "#c1c1c1",
                        }}
                        onDoubleClick={() => {
                          navigate(
                            `/slide/detail?title=${fatherItem.slideTitle}&id=${fatherItem.id}`
                          );
                        }}
                      >
                        {/* 缩略图展示---仅仅展示一张幻灯片 */}
                        {/* <SuoLueTu fatherItem={fatherItem} /> */}
                      </div>
                      <div
                        style={{
                          width: "100%",
                          height: 80,
                          padding: "8px 16px",
                        }}
                      >
                        <div
                          style={{
                            overflow: "hidden",
                            color: "#333",
                            fontWeight: "bold",
                            fontSize: 20,
                            whiteSpace: "nowrap",
                            textOverflow: "ellipsis",
                          }}
                        >
                          {fatherItem?.slideTitle}
                        </div>
                        <div style={{ float: "right", marginTop: 1 }}>
                          <span>共{fatherItem?.slideList.length}张</span>
                          <Popconfirm
                            title="确定要删除该幻灯片吗?"
                            onConfirm={() => {
                              gotoCancle(fatherIndex);
                            }}
                            okText="是"
                            cancelText="否"
                          >
                            <DeleteOutlined
                              style={{
                                fontSize: 20,
                                marginLeft: 18,
                                cursor: "pointer",
                              }}
                            />
                          </Popconfirm>
                          <PlayCircleOutlined
                            onClick={() => {
                              // navigate(
                              // );
                              window.open(
                                `/slide/read?title=${fatherItem.slideTitle}&id=${fatherItem.id}`,
                                "_blank"
                              );
                            }}
                            style={{
                              fontSize: 20,
                              marginLeft: 18,
                              cursor: "pointer",
                            }}
                          />
                          <EditOutlined
                            // onDoubleClick={() => {
                            //   navigate(
                            //     `/slide/detail?title=${fatherItem.slideTitle}&id=${fatherItem.id}`
                            //   );
                            // }}
                            onClick={() => {
                              navigate(
                                `/slide/detail?title=${fatherItem.slideTitle}&id=${fatherItem.id}`
                              );
                              updateAnyData({
                                slideImage: fatherItem?.slideImage, //标题
                              });
                            }}
                            style={{
                              fontSize: 20,
                              marginLeft: 18,
                              cursor: "pointer",
                            }}
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <Empty />
          )}
        </>
      </Spin>
      <Modal
        width={400}
        title="设置幻灯片"
        open={modalVisible}
        onCancel={handleCancel}
        onOk={handleOK}
        okText="创建"
        cancelText="取消"
      >
        <div>
          <>
            标题：
            <Input
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
            />
          </>
          <div>
            缩略图URl：
            <Input
              value={inputValue2}
              onChange={(e) => setInputValue2(e.target.value)}
            />
          </div>
          {/* {selectValue === "color" ? (
            <>
              设置颜色：（例如:#000000）
              <Input
                value={backgroundVal}
                onChange={(e) => setbackgroundVal(e.target.value)}
              />
            </>
          ) : null}
          {selectValue === "gradient" ? (
            <>
              设置渐变色：（例如:#000000）
              <div style={{ display: "flex" }}>
                <Input
                  style={{ width: 100 }}
                  value={backgroundVal}
                  onChange={(e) => setbackgroundVal(e.target.value)}
                />
                到
                <Input
                  style={{ width: 100 }}
                  value={backgroundVal2}
                  onChange={(e) => setbackgroundVal2(e.target.value)}
                />
              </div>
            </>
          ) : null}
          {selectValue === "img" ? (
            <>
              设置图像地址：
              <Input
                value={backgroundVal}
                onChange={(e) => setbackgroundVal(e.target.value)}
              />
            </>
          ) : null} */}
        </div>
      </Modal>
    </div>
  );
};

export default SlideList;
